#include "../core/engine/interface.h"
#include "../core/engine/world.h"
#include "button.h"

namespace sleek
{
    namespace gui
    {
        button::button(core::engine::interface *m) : frame(m)
        {
            hovored = pushed = false;
        }
        button::~button()
        {
        }
        bool button::isPushed()
        {
            return pushed;
        }
        bool button::isHovored()
        {
            return hovored;
        }
        void button::UpdateFontPos()
        {
            textpos = absolute+relative;
            textpos += box.getSize()/2;
            textpos.width -= ft2->getBoxSize().width/2;
            textpos.height += 2;
        }
        bool button::manage(core::device::input* e)
        {
            bool CHovored = hovored, CPushed = pushed;
            if(frame::manage(e)) { pushed = hovored; hovored = false; return true; }

            if(e->type == core::device::EVENT_MOUSSE_MOVED) hovored = box.intersect(e->mouse_pos);
            if(e->type == core::device::EVENT_MOUSSE_DOWN && e->mouse[core::device::MOUSE_LEFT] && hovored) pushed = true;
            if(e->type == core::device::EVENT_MOUSSE_UP && e->mouse[core::device::MOUSE_LEFT])
            {
                if(hovored && pushed)
                {
                    pushed = false;
                    e->gui.called = this;
                    e->gui.code = gui::IET_BUTTON_CLICKED;
                    return true;
                }
                pushed = false;
            }

            if(CPushed != pushed && pushed)
            {
                e->gui.called = this;
                e->gui.code = gui::IET_BUTTON_PUSHED;
                return true;
            }
            if(CHovored != hovored)
            {
                e->gui.called = this;
                if(hovored) e->gui.code = gui::IET_BUTTON_HOVERED;
                else e->gui.code = gui::IET_BUTTON_FOCUSED;
                return true;
            }
            return false;
        }
        void button::render()
        {
            if(!show) return;

            if(pushed && hovored) mom->getTheme()->drawButtonPushed(this);
            else if(hovored && !pushed) mom->getTheme()->drawButtonHovored(this);
            else mom->getTheme()->drawButton(this);

            if(ft2) mom->getTheme()->drawFont(this);
            renderChild();
        }
    }
}
